﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace VNet.VisiSuite.Common.Helper
{
    /// <summary>
    ///     Password helper class
    /// </summary>
    public static class EncryptionHelper
    {
        /// <summary>
        ///     Salts the generator.
        /// </summary>
        /// <returns></returns>
        public static string SaltGenerator()
        {
            var buffer = new byte[16];
            using (var provider = new RNGCryptoServiceProvider())
            {
                provider.GetBytes(buffer);
                return Convert.ToBase64String(buffer);
            }
        }

        /// <summary>
        ///     Encodes the password.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <returns></returns>
        public static string EncodePassword(string password)
        {
            byte[] bytesIn = Encoding.Unicode.GetBytes(password);
            byte[] bytesReturn;
            using (HashAlgorithm hashAlgorithm = HashAlgorithm.Create())
            {
                bytesReturn = hashAlgorithm.ComputeHash(bytesIn);
            }
            return Convert.ToBase64String(bytesReturn);
        }

        /// <summary>
        ///     Encodes the string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="salt">The salt.</param>
        /// <returns></returns>
        public static string EncodeString(string value, string salt)
        {
            byte[] bytesIn = Encoding.Unicode.GetBytes(value);
            byte[] bytesSalt = Convert.FromBase64String(salt);
            var bytesAll = new byte[bytesIn.Length + bytesSalt.Length];
            byte[] bytesReturn;
            Buffer.BlockCopy(bytesSalt, 0, bytesAll, 0, bytesSalt.Length);
            Buffer.BlockCopy(bytesIn, 0, bytesAll, bytesSalt.Length, bytesIn.Length);
            using (HashAlgorithm hashAlgorithm = HashAlgorithm.Create())
            {
                bytesReturn = hashAlgorithm.ComputeHash(bytesAll);
            }
            return Convert.ToBase64String(bytesReturn);
        }
    }
}